﻿using System;
using System.Linq;
using XRM.Security.DataAccess.Enums;
using XRM.Security.DataAccess.Interfaces;
using XRM.Security.DataAccess.Models;

namespace XRM.Security.DataAccess.Helpers
{
    public static class QueryExtensions
    {
        public static IQueryable<UserRegister> FilterByFullName<T>( this IQueryable<T> query, string term ) where T : class, IUserRegister
        {
            return query.Select( s => s.UserRegister ).FilterByFullName(term).Distinct();
        }

        public static IQueryable<UserRegister> FilterByFullName(this IQueryable<UserRegister> query, string term)
        {
            return query.Where( x => ( x.LastName + " " + x.FirstName + " " + x.MotherName ).StartsWith( term ) );
        }

        public static IQueryable<Request> OpenRequests (this IQueryable<Request> query)
        {
            return query.Where( s => s.Status == (int)RequestStatus.InWork || s.Status == (int)RequestStatus.InPart );
        }

        public static IQueryable<CertRegister> ExpiredCertificates( this IQueryable<CertRegister> query, int expiredDays )
        {
            var maxExpiredDate = DateTime.Today.AddDays( expiredDays + 1 );
            return query.Where( s => s.ToDate >= DateTime.Today && s.ToDate <= maxExpiredDate );
        }

        public static bool Exists<T>( this IQueryable<T> query, string thumbprint ) where T : class, ICertificate
        {
            return query.Any( s => s.Thumbprint == thumbprint );
        }

        public static IQueryable<T> Actual<T>( this IQueryable<T> query ) where T : class, IRemovable
        {
            return query.Where( s => !s.IsDeleted );
        }

        public static IQueryable<CertRegister> ValidCertificates( this IQueryable<CertRegister> query )
        {
            return query.Where( s => s.ToDate >= DateTime.Today && s.UserRegister.Status == (int)UserStatus.Work );
        }
    }
}
